package com.a.lib_network.http

import androidx.appcompat.app.AppCompatActivity

import com.hjq.http.EasyHttp
import com.hjq.http.config.IRequestApi
import com.hjq.http.listener.OnHttpListener
import com.a.lib_bean.callback.MyConsumer
import com.a.lib_network.bean.HttpData
import com.a.lib_bean.callback.Fail
import com.a.lib_utils.TipUtil
import com.a.lib_utils.TipUtil.delayDismiss
import com.a.lib_utils.TipUtil.failTip
import com.a.lib_utils.TipUtil.loadingTip

import okhttp3.Call

/**
 * 只适用于HttpData和activity
 * 坑货获取的是第一个泛型，HttpDataCallBack的T而非OnHttpListener的HttpData<Bean>
 * */
@Deprecated("不在Activity请求，造成代码冗余，现改为用LiveDataHttpCallBack", ReplaceWith("LiveDataHttpCallBack()"))
abstract class HttpDataCallBack<T, Bean>(context: AppCompatActivity) : OnHttpListener<HttpData<Bean>> {
    private val context: AppCompatActivity
    lateinit var consumer: MyConsumer<Bean>
    var fail: Fail? = null

    init {
        this.context = context
    }

    fun get(api: IRequestApi, fail: Fail, consumer: MyConsumer<Bean>) {
        this.fail = fail
        this.consumer = consumer
        EasyHttp.get(context).api(api)
            .request(this)
    }

    fun get(api: IRequestApi, consumer: MyConsumer<Bean>) {
        this.consumer = consumer
        EasyHttp.get(context).api(api)
            .request(this)
    }

    override fun onStart(call: Call?) {
        super.onStart(call)
        loadingTip(context, "正在加载")
    }

    override fun onSucceed(result: HttpData<Bean>, cache: Boolean) {
        super.onSucceed(result, cache)
    }

    override fun onSucceed(result: HttpData<Bean>) {
        if (!result.isSuccess) {
            if (fail == null) TipUtil.tip(context, result.msg)
            else fail?.onFail()
            return
        }
        if (result.data == null) TipUtil.toast("数据为空")
        else consumer.accept(result.data)
    }

    override fun onFail(e: Exception) {
        failTip(context, e.toString())
    }

    override fun onEnd(call: Call) {
        super.onEnd(call)
        delayDismiss(500)
    }


}
